/*
 * @Author: yzr
 * @Date: 2023-09-08 14:25:41
 * @LastEditors: yzr
 * @LastEditTime: 2023-09-25 16:46:41
 * @Description:
 * @FilePath: /utilization/src/layouts/breadcrumb/index.tsx
 */
import React from 'react';
import { Breadcrumb } from 'antd';
import type { BreadcrumbItemType } from 'antd/es/breadcrumb/Breadcrumb';
import { useMatches, Link } from 'react-router-dom';
import type { Params } from 'react-router-dom';

type MatchesType = {
  id: string;
  pathname: string;
  params: Params<string>;
  data: unknown;
  handle: any;
};
const BreadcrumbSelf: React.FC = () => {
  let matches = useMatches();
  function getBreadcrumbs(): Array<BreadcrumbItemType> {
    const normalBread: Array<MatchesType | BreadcrumbItemType> = matches.filter(
      item => {
        return !!(item.handle as any).title && item.pathname !== '/';
      }
    );
    let crumbs = [];
    for (let i = 0; i < normalBread.length; i++) {
      if ('handle' in normalBread[i]) {
        let currentBread = normalBread[i] as MatchesType;
        let parent = currentBread.handle.parent;
        if (parent && parent.title) {
          let result = {
            path: parent.path,
            title: parent.title,
          };
          crumbs.push(result);
          crumbs.push({
            path: currentBread.pathname,
            title: currentBread.handle.title,
          });
          normalBread.splice(i, 0, result as BreadcrumbItemType);
          i++;
        } else {
          crumbs.push({
            path: currentBread.pathname,
            title: currentBread.handle.title,
          });
        }
      }
    }
    return crumbs;
  }
  let crumbs = getBreadcrumbs();
  const itemRender = (
    item: BreadcrumbItemType,
    params: any,
    items: BreadcrumbItemType[],
    paths: any
  ) => {
    const last = items.indexOf(item) === items.length - 1;
    return last ? (
      <span>{item.title}</span>
    ) : (
      <Link to={paths.join('#')}>{item.title}</Link>
    );
  };
  if (crumbs && crumbs.length > 1) {
    return (
      <>
        <Breadcrumb
          items={crumbs}
          itemRender={itemRender}
          style={{ padding: '16px' }}></Breadcrumb>
      </>
    );
  } else {
    return <></>;
  }
};

export default BreadcrumbSelf;
